#include "simdata_tcpsever.h"
#include<QDebug>

SimData_TcpSever::SimData_TcpSever(QObject *parent) : QObject(parent)
{
    m_TcpSever = new QTcpServer();
    m_TcpSever->listen(QHostAddress::Any, 1989);
    connect(m_TcpSever,SIGNAL(newConnection()),this,SLOT(new_client()));
}

SimData_TcpSever::~SimData_TcpSever()
{
    m_ListUdpSever.clear();
    m_TcpSocket->close();
    m_TcpSever->close();
    delete m_TcpSocket;
    delete m_TcpSever;
}

void SimData_TcpSever::hz(int hz)
{
    qDebug() << "SimData_TcpSever HZ:" << hz;
    m_HZ = hz;
}

void SimData_TcpSever::dataStart()
{
    for (int i = 0; i < m_ListUdpSever.count(); i++) {
        m_ListUdpSever.at(i)->start();
    }

}

void SimData_TcpSever::dataStop()
{
    for (int i = 0; i < m_ListUdpSever.count(); i++) {
        m_ListUdpSever.at(i)->quit();
        m_ListUdpSever.at(i)->deleteLater();
    }
    m_ListUdpSever.clear();
}

void SimData_TcpSever::new_client()
{
    m_TcpSocket = m_TcpSever->nextPendingConnection();
    connect(m_TcpSocket,SIGNAL(readyRead()),this,SLOT(read_client_data()));
    connect(m_TcpSocket,SIGNAL(disconnected()),this,SLOT(client_dis()));

}

void SimData_TcpSever::read_client_data()
{
    QTcpSocket *obj = (QTcpSocket*)sender();
    QString msg = obj->readAll();
    QStringList msgList = msg.split("-");
    if(msgList.count() == 2) obj->write("connect");
    else{
        obj->write("erro");
        return;
    }
    QString name = msgList.at(0);
    QString port = msgList.at(1);
    emit client(name, obj->peerAddress() ,port.toInt());
    m_ListUdpSever.append(new SimData_UdpSever(name, obj->peerAddress(), port.toInt(), m_HZ));
}

void SimData_TcpSever::client_dis()
{
    QTcpSocket *obj = (QTcpSocket*)sender();
    qDebug() << "Terminal dis :" << obj->peerAddress();
}



